package com.xiyuan.almighty.service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @创建人 袁继鑫
 * @创建时间 2021-04-02 18:18
 * @版本 1.0
 * @描述
 */
//生产者、消费者
public class TestProducerConsumer {
    public static void main(String[] args) {

        MyStack stack = new MyStack();


        new Thread(() -> {
            for (char c = 'A'; c <= 'Z'; c++) {
                stack.push(c + "");
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 1; i <= 26; i++) {
                stack.pop();
            }
        }, "B").start();

    }
}

class MyStack {
    String[] data = {"", "", "", "", "", ""};
    int index;

    Lock lock = new ReentrantLock();
    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();

    public void push(String s) {
        try {
            lock.lock();
            while (data.length == index) {
//                System.out.println("开始等待，不再生产");
                try {
                    full.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print(s + " pushed   ");
            data[index] = s;
            index++;
            print();
            empty.signalAll();//通知消费者
        } finally {
            lock.unlock();
        }
    }

    public void pop() {
        try {
            lock.lock();
            while (index == 0) {
                try {
//                    System.out.println("开始等待，不再消费");
                    empty.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            index--;
            String o = data[index];
            data[index] = "";
            System.out.print(o + " poped    ");
            print();
            full.signalAll(); //通知生产者
        } finally {
            lock.unlock();
        }
    }

    public void print() {
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i] + " ");
        }
        System.out.println();
    }
}
